package dnet

import (
	"fmt"
	"net"
)

func IpV4ToUDPBoradIP(localipv4 string) string {
	ipV4Bytes := IpV4Bytes(localipv4)
	if ipV4Bytes[0] == 0 && ipV4Bytes[1] == 0 {
		return ""
	}
	return fmt.Sprintf("%d.%d.%d.255", ipV4Bytes[0], ipV4Bytes[1], ipV4Bytes[2])
}

func UDPSend(conn *net.UDPConn, raddr string, buf []byte) (int, error) {
	addr, err := net.ResolveUDPAddr("udp", raddr)
	if err != nil {
		return 0, err
	}

	return conn.WriteToUDP(buf, addr)
}

func NewUDPOpera(localaddr string, onrecv func(conn *net.UDPConn, fromaddr *net.UDPAddr, buf []byte)) (conn *net.UDPConn, err error) {
	addr, err := net.ResolveUDPAddr("udp", localaddr)
	if err != nil {
		return nil, err
	}

	conn, err = net.ListenUDP("udp", addr)
	if err != nil {
		return nil, err
	}

	go func() {
		rcvBuf := make([]byte, 512)
		for {
			n, addr, err := conn.ReadFromUDP(rcvBuf)
			if err != nil {
				break
			}
			if onrecv != nil {
				onrecv(conn, addr, rcvBuf[:n])
			}
		}
	}()

	return conn, nil
}
